package com.local.cart.rabbitmq;

import com.local.cart.constants.CartConstants;
import com.local.cart.service.ShoppingCartService;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 消息消费者，监听购物车id列表，然后删除这些数据
 */
@Component
public class RabbitMQConsumer {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @RabbitListener(queuesToDeclare = @Queue(CartConstants.CART_DELETE_QUEUE))
    public void cartDeleteQueueConsumer(String cartItemIds) { // cartItemIds: 1,2,3
        System.out.println("message cartItemIds："+cartItemIds);
        if (Objects.nonNull(cartItemIds) && cartItemIds.length() > 0) {
            String[] cartItemIdArr = cartItemIds.split(",");
            List<Integer> cartItemIdList = Arrays.stream(cartItemIdArr).map(new Function<String, Integer>() {
                @Override
                public Integer apply(String s) {
                    return Integer.valueOf(s);
                }
            }).collect(Collectors.toList());

            Integer deleteResult = shoppingCartService.deleteByIds(cartItemIdList);
            if (Objects.nonNull(deleteResult) && deleteResult > 0) {
                //System.out.println("处理cartItemIds成功："+cartItemIds);
            } else {
                System.out.println("message cartItemIds failed："+cartItemIds);
            }
        }

    }
}
